package com.kaf.ai.service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.kaf.ai.dto.ChatRequest;
import com.kaf.ai.dto.ChatResponseChunk;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Flux;
@Slf4j
@Service
public class DeepSeekService {

    private final WebClient webClient;
    private final ObjectMapper objectMapper = new ObjectMapper();

    public DeepSeekService(WebClient webClient) {
        this.webClient = webClient;
    }

    public Flux<String> streamChatCompletion(ChatRequest request) {
        log.info("开始流式聊天请求，模型: {}，消息数: {}", request.getModel(), request.getMessages().length);
        log.info("请求内容: {}", request);

        return webClient.post()
                .uri("/chat/completions")
                .bodyValue(request)
                .retrieve()
                .bodyToFlux(String.class)
                .doOnNext(raw -> log.info("原始响应: {}", raw))
                .filter(chunk -> {
                    // 过滤空块和结束标记
                    boolean isValid = !chunk.trim().isEmpty() &&
                            !chunk.equals("[DONE]") &&
                            !chunk.contains("\"finish_reason\":\"stop\"");

                    if (!isValid) {
                        log.debug("过滤无效块: {}", chunk.length() > 50 ? chunk.substring(0,50)+"..." : chunk);
                    }

                    return isValid;
                })
                .map(this::parseChunk)
                .filter(content -> {
                    // 处理空内容
                    if (content == null) {
                        log.info("过滤空内容块");
                        return false;
                    }

                    if (content.isEmpty()) {
                        log.debug("收到空内容块");
                        return false;
                    }

                    return true;
                })
                .doOnNext(content -> log.info("发送内容块: {}", content))
                .doOnComplete(() -> log.info("流式响应完成"))
                .doOnError(e -> log.error("流式处理错误", e));
    }

    private String parseChunk(String jsonChunk) {
        try {
            log.info("解析JSON块: {}", jsonChunk);

            // 特殊处理结束标记
            if ("[DONE]".equals(jsonChunk)) {
                log.info("收到流式结束标记");
                return null;
            }

            ChatResponseChunk chunk = objectMapper.readValue(jsonChunk, ChatResponseChunk.class);

            // 记录使用情况（如果有）
            if (chunk.getUsage() != null) {
                log.debug("Token使用: 提示={}, 完成={}, 总计={}",
                        chunk.getUsage().getPrompt_tokens(),
                        chunk.getUsage().getCompletion_tokens(),
                        chunk.getUsage().getTotal_tokens());
            }

            // 验证是否有有效的choices
            if (chunk.getChoices() == null || chunk.getChoices().length == 0) {
                log.warn("解析块中无choices: {}", jsonChunk);
                return null;
            }

            ChatResponseChunk.Choice choice = chunk.getChoices()[0];

            // 检查是否是结束块
            if (choice.getFinish_reason() != null) {
                log.info("收到结束块，原因: {}", choice.getFinish_reason());
                return null;
            }

            // 获取delta对象
            ChatResponseChunk.Choice.Delta delta = choice.getDelta();
            if (delta == null) {
                log.warn("解析块中无delta: {}", jsonChunk);
                return null;
            }

            // 返回内容（可能为空）
            return delta.getContent();
        } catch (JsonProcessingException e) {
            log.error("JSON解析错误: {}", e.getMessage());
            log.warn("解析失败的JSON块: {}", jsonChunk);
            return null;
        }
    }
}
